<?php


namespace app\admin\model;


use app\sys\model\Dict;
use app\sys\model\UrlSourceLog;
use Kqtec\IpLocationZh\Ip;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\facade\Env;
use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = true;


    public function setIconAttr($value)
    {
        if(strlen($value) > 255){
            return "";
        }
        return $value;
    }

    public function getIconAttr($value)
    {
        $gwHt = Env::get("GW.HTTP");
        return $gwHt.$value;
    }

    /**
     * @param $chatId
     * @param $userNo
     * @param $staffInfo
     * @return User|string
     * 用户信息
     */
    public static function info($chatId,$userNo,$staffInfo)
    {
        $chat = Chat::where("id",$chatId)
            ->where("user_no",$userNo)
            ->where("staff_no",$staffInfo["staff_no"])
            ->find();
        if(!$chat){
            return "";
        }
        $user = User::where("id",$chat["user_id"])->find();
        // 不是会员，获取卡片电话
        if(isset($user["mobile"]) && $user["mobile"]==""){
            $user["mobile"] = Card::where("user_no",$user["no"])->where("staff_no",$staffInfo["staff_no"])->order("id desc")->value("mobile");
        }
        return $user;
    }

    /**
     * @param $userNo
     * @param $mobile
     * @param $sex
     * @param $name
     * @param $remark
     * @param int $store_type 店铺类型 找店 转店 其他
     * @param string $gather
     * @return string
     * 极速通道 留意 客服保存客户信息
     */
    public static function saveInfo($userNo,$mobile,$sex,$name,$remark,$store_type = 0,$gather = "",$staffNo = "",$url = "")
    {
        $user = User::where("no",$userNo)->find();
        if(!$user){
            return "用户不存在~";
        }
//        if($mobile && ($user['mobile'] != $mobile)){
//            return "会员手机号不能修改~";
//        }
        $user['no'] = $userNo;
//        $user['mobile'] = $mobile;
        $user['sex'] = $sex;
        $user['name'] = $name;

        if($url){
            $user["url"] = $url;
        }else{
            $user["url"] = UrlSourceLog::getUrlIng($userNo);
        }

        $user["is_card"] = 1;

        $storeTypeName = "";
        if ($store_type){
            $user['store_type'] = $store_type;
            $storeTypeName = Dict::getLabel("store_type",$store_type);
        }
        $user['remark'] = $remark.$storeTypeName;
        $user["gather_method"] = $gather;
        Db::startTrans();
        try{
            Card::add($userNo,$staffNo,$mobile);
            $res = $user->isUpdate(true)->save();
            if(!$res){
                Db::rollback();
                return "添加失败~";
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return "添加失败~";
        }
        return "";
    }

    public static function getIsUserMember($userNo,$mobile)
    {

        if($mobile){
            // 会员以电话标识
            $u = User::where("mobile",$mobile)->column("no");
            if(!$u){
                return ["","用户不存在"];
            }

            $user_id = Chat::where("user_no","in",$u)->value("user_id");
            if(!$user_id) return ["","用户不存在"];

            $userInfo = user::where("id",$user_id)->find();
            if($userInfo)
            {
                return [$userInfo,""];
            }
        }else{
            // 游客
            $userDate = User::where("no",$userNo)->find();
            if ($userDate){
                return [$userDate,""];
            }
        }

        return ["","用户不存在"];
    }

    /**
     * @param $data
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserList($f,$data,$page = 0,$limit = 10)
    {
        $userSql = Card::alias("c")
            ->field($f)
            ->leftJoin("ic_user u","u.no = c.user_no")
            ->leftJoin("ic_staff is","is.staff_no = u.staff_no")
            ->where("is_card",1)->order("c.id desc");

        $userSql = Duty::getQueryByDataPermId($userSql,"c.staff_no");
        if(isset($data["mobile"]) && $data["mobile"]){
            $userSql = $userSql->where("c.mobile",$data["mobile"]);
        }

        // 站点
        if(isset($data["site"])&& $data["site"]){
            $label = Dict::where("cate","site")->where("value",$data["site"])->value("label");
            $userSql = $userSql->where("u.site",$label);
        }
        // 来源
        if(isset($data["source"]) && $data["source"]){
            $label = Dict::where("cate","source")->where("value",$data["source"])->value("label");
            $userSql = $userSql->where("u.source",$label);
        }
        // 方法
        if(isset($data["gather_method"]) && $data["gather_method"] ){
            $userSql = $userSql->where("u.gather_method",$data["gather_method"]);
        }
        // 总数
        if(isset($data["date_arr"]) &&  $data["date_arr"]){
            $data["date_arr"][0] = strtotime($data["date_arr"][0]);
            $data["date_arr"][1] = strtotime($data["date_arr"][1]);
            $userSql = $userSql->whereBetween("u.create_time",$data["date_arr"]);
        }
        $listC = $userSql->count();
        $list = $userSql->page($page,$limit)->select();


        return listDate($list,$listC);
    }

    /**
     * @param $data
     * @param $staffNo
     * @param $ip
     * @return array
     * 聊天添加用户信息
     */
    public static function addChatUser($data,$staffNo,$ip,$url):array
    {
        //判断是会员还是游客
        $reUserSql = new User;
        if (isset($data["mobile"]) && !empty($data["mobile"])) {
            $mobile = $data["mobile"];
            $reUserSql = $reUserSql->where("mobile", $mobile);
        } else {
            $reUserSql = $reUserSql->where("no", $data["user_no"]);
            $mobile = "";
        }

        // 新用户
        $reUser = $reUserSql->find();
        if (!$reUser) {

            $area = "";
            $address = "";
            // 获取url
            $source = UrlSourceLog::getSource($data["user_no"]);
            $url = UrlSourceLog::getUrlIng($data["user_no"]);
            // 获取地址
            $arrAr = Ip::find($ip)["location"];
            if (!empty($arrAr)) {
                $area = $arrAr[1];
                $address = implode("/", array_slice($arrAr, 1));
            }
            $icon = UserPvLog::where("user_no",$data["user_no"])->order("id desc")->value("user_icon","");
            // 获取一个页面URL
            $arr = [
                "name" => "客户{$data["user_no"]}",
                "mobile" => $mobile,
                "no" => $data["user_no"],
                "source" => $source[0],
                "source_url"=>$source[1],
                "area" => $area,
                "address" => $address,
                "duty_id" => $data["duty_id"],
                "server_type" => $data["server_type"],
                "gather_method" => "客服获取",
                "staff_no" => $staffNo,
                "url" => $url,
//                "url" => $de,
                "wp" => "页面不知",
                "site"=>UrlSourceLog::getSite(getComeUrl()),
//                "site"=>UrlSourceLog::getSite($de),
                "icon"=>$icon
            ];

            $reUse = User::create($arr);
            $userId = $reUse->id;
            $isMen = empty($mobile) ? 0 : 1;
        } else {
            // 旧用户
            $userId = $reUser->id;
            $isMen = empty($mobile) ? 0 : 1;
        }
        // 用户id 是否是会员
        return [$userId,$isMen];
    }

    //修改在职状态
    public static function deleteTime($staffNo)
    {
       Staff::where("staff_no",$staffNo)->data(["delete_time"=>0])->update();
    }

    // 是否是会员
    public static function getIsMen($mobile):int
    {
        $isMen = 0;
        if ($mobile) $isMen = 1;
        return $isMen;
    }

    // 是否是会员
    public static function getIsMenByUser($no):int
    {
        $mobile = user::where("no",$no)->value("mobile");
        return self::getIsMen($mobile);
    }
}